package edu.kpi.pzks2.graph;

import java.awt.geom.Point2D;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import edu.uci.ics.jung.algorithms.layout.AbstractLayout;
import edu.uci.ics.jung.graph.util.Pair;

/**
 * Is used for graph serialization.
 *
 * @author Pustovit Michael, pustovitm@gmail.com
 */
public class GraphBundle implements Serializable {
    private static final long serialVersionUID = -4657636624245250838L;
    
    final List<NodeDescriptor> nodes;
    final List<EdgeDescriptor> edges;
    
    public GraphBundle(AbstractLayout<Node, Edge> layout) {
        nodes = new ArrayList<NodeDescriptor>();
        edges = new ArrayList<EdgeDescriptor>();
        
        for (Node node : layout.getGraph().getVertices()) {
            nodes.add(new NodeDescriptor(node, new Point2D.Double(layout.getX(node), layout.getY(node))));
        }
        
        for (Edge edge : layout.getGraph().getEdges()) {
            edges.add(new EdgeDescriptor(edge, layout.getGraph().getEndpoints(edge)));
        }
    }    
    
    public List<NodeDescriptor> getNodes() {
        return nodes;
    }
    
    public List<EdgeDescriptor> getEdges() {
        return edges;
    }
    
    @Override
    public String toString() {
        final StringBuilder str = new StringBuilder();
        
        for (NodeDescriptor n : nodes) {
            str.append(n.getNode() + " ");
        }
        
        str.append("\n");
        
        for (EdgeDescriptor e : edges) {
            str.append(e.getEdge() + " ");
        }
        
        return str.toString();
    }
    
    public class NodeDescriptor implements Serializable {
        private static final long serialVersionUID = 6773911163932173505L;
        
        private Node node;
        private Point2D.Double pos;
        
        public NodeDescriptor(Node node, Point2D.Double pos) {
            this.node = node;
            this.pos = pos;
        }
        
        public Node getNode() {
            return node;
        }
        
        public Point2D getPos() {
            return pos;
        }
    }
    
    public class EdgeDescriptor implements Serializable {
        private static final long serialVersionUID = -7886919044208712041L;
        
        private Edge edge;
        private Pair<Node> pair;
        
        public EdgeDescriptor(Edge edge, Pair<Node> pair) {
            this.edge = edge;
            this.pair = pair;
        }
        
        public Edge getEdge() {
            return edge;
        }
        
        public Pair<Node> getPair() {
            return pair;
        }
    }
}
